package com.polaris.live.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.widget.AppCompatTextView
import com.polaris.live.R

/**
 * 边框文字   写这个因为shapeTextView不会自动换行
 *
 * @author Created by 半仙 on 2024/7/26/026 14:15
 */
class StrokeTextView(context: Context, attrs: AttributeSet?) : AppCompatTextView(context, attrs) {

    private val outlineTextView by lazy { TextView(context, attrs) }

    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.StrokeTextView)
        val color = typedArray.getColor(R.styleable.StrokeTextView_stroke_color, 0)
        val dimension = typedArray.getDimension(R.styleable.StrokeTextView_stroke_width, 0f)
        typedArray.recycle()

        setStrokeColor(color)
        setStrokeWidth(dimension)

        outlineTextView.gravity = gravity
    }

    fun setStrokeColor(color: Int) {
        outlineTextView.setTextColor(color)
    }

    fun setStrokeWidth(width: Float) {
        outlineTextView.paint.strokeWidth = width
        outlineTextView.paint.style = Paint.Style.STROKE
    }

    override fun setLayoutParams(params: ViewGroup.LayoutParams) {
        super.setLayoutParams(params)
        outlineTextView.layoutParams = params
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        // 设置轮廓文字
        val outlineText = outlineTextView.text
        if (outlineText == null || outlineText != this.text) {
            outlineTextView.text = text
            postInvalidate()
        }
        outlineTextView.measure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        outlineTextView.layout(left, top, right, bottom)
    }

    override fun onDraw(canvas: Canvas) {
        outlineTextView.draw(canvas)
        super.onDraw(canvas)
    }
}
